import {defineStore} from "pinia";
import {ref, watch} from "vue";
import {getMemberList, MemberDelete, MemberUpdate} from "@/services/api/organization/member.ts";
import {useOrgStore} from "@/store/modules/organization/index.ts";
import useMessage from "@/utils/useMessage.ts";
import {hasPermission} from "@/utils/permission.ts";

export const useMemberStore = defineStore('member',()=>{
    const dataSource = ref<MemberListType[]>([])
    const loading = ref<boolean>(false)
    const orgStore = useOrgStore()
    const getList = async (force?:boolean)=>{
        if(!force && dataSource.value.length > 0){
            return
        }
        loading.value = true
        try {
            const res:ApiResponse<MemberListType[]> = await getMemberList(orgStore.id)
            if(res.code === 200){
                dataSource.value = res.data
            }else {
                useMessage(500,res.message)
            }
        }catch{}
        finally {
            setTimeout(()=>loading.value = false,100)
        }
    }
    const update = async (id:number,params:object)=>{
        if(!hasPermission('member:update')) return false;
        const res = await MemberUpdate(id,params)
        if(res.code === 200){
            await getList(true)
        }else {
            useMessage(500,res.message)
        }
        return res.code === 200
    }
    const remove = async (id:number)=>{
        if(!hasPermission('member:delete')) return false;
        const res = await MemberDelete(id)
        if(res.code === 200){
            dataSource.value = dataSource.value.filter(item=>item.id !== id)
        }else {
            useMessage(500,res.message)
        }
        return res.code === 200
    }
    watch(()=>orgStore.id,async ()=>{
        await getList(true)
    })
    return {dataSource,getList,loading,update,remove}
},{ persist: { omit: ['loading']} })